package com.shenghui.enterprise.enterprise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenghui.enterprise.base.entity.Page;
import com.shenghui.enterprise.base.entity.PageModel;
import com.shenghui.enterprise.enterprise.entity.EntBasicInfo;
import com.shenghui.enterprise.enterprise.mapper.EntBasicInfoMapper;
import com.shenghui.enterprise.enterprise.service.IEntBasicInfoService;
import com.shenghui.enterprise.utils.GeneralUtil;
import com.shenghui.enterprise.utils.MD5;
import com.shenghui.enterprise.utils.UserUtil;
import com.shenghui.enterprise.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @Description: 企业基础信息表业务逻辑实现类
 * @Author tt
 * @Email: happyxiaohou@gmail.com
 * @Date: 2020-10-13
 * @Copyright (c) 2020-2022 云南昇晖科技有限公司
 */
@Service
@Transactional
public class EntBasicInfoServiceImpl extends ServiceImpl<EntBasicInfoMapper, EntBasicInfo> implements IEntBasicInfoService {

    @Autowired
    private EntBasicInfoMapper entBasicInfoMapper;
    @Autowired
    private UserUtil userUtil;

    @Override
    public Result register(EntBasicInfo entBasicInfo) {
        String code = entBasicInfo.getEntCode();
        EntBasicInfo entBasicInfos = entBasicInfoMapper.selectOne(new QueryWrapper<EntBasicInfo>().lambda()
                .eq(EntBasicInfo::getEntCode, code));
        if(GeneralUtil.isNotNull(entBasicInfos)){
            return Result.error("统一社会信用代码已存在，不能重复注册");
        }
        entBasicInfo.setPwd(MD5.MD5Encode(entBasicInfo.getPwd()));
        entBasicInfo.setRegisterTime(LocalDate.parse(entBasicInfo.getRegisterTimeStr()));
        entBasicInfo.setCreateDate(LocalDateTime.now());
        entBasicInfoMapper.insert(entBasicInfo);
        return Result.ok("恭喜您，注册成功！");
    }

    @Override
    public PageModel findList(Map map) {
        Page<Map> mapPage = new Page<>(map);
        IPage iPage = entBasicInfoMapper.selectPage(mapPage, new QueryWrapper<EntBasicInfo>()
                .lambda()
                .like(GeneralUtil.isNotNull(map.get("entName")), EntBasicInfo::getEntName, map.get("entName")));
        return new PageModel(iPage.getTotal(), iPage.getRecords());
    }

    @Override
    public Result resetPassword(Map map) {
        EntBasicInfo frontLoginUser = userUtil.getFrontLoginUser();
        if(!MD5.MD5Encode(map.get("oldPass").toString()).equals(frontLoginUser.getPwd())){
            return Result.error("输入的旧密码不正确，请重新输入!");
        }
        frontLoginUser.setPwd(MD5.MD5Encode(map.get("newPass").toString()));
        entBasicInfoMapper.updateById(frontLoginUser);
        return Result.ok("密码修改成功!");
    }
}
